<?php
/**
 * Created by PhpStorm.
 * User: yellow
 * Date: 2019/5/27
 * Time: 13:12
 */

namespace app\admin\logic;


use app\admin\logic\code\ErrorCode;
use app\common\model\Bus;
use app\common\model\BusImg;
use think\Db;

class BusLogic extends BaseLogic
{

    private $busModel;
    private $busImgModel;

    public function __construct()
    {
        parent::__construct();
        $this->busModel = new Bus();
        $this->busImgModel = new BusImg();
    }

    /**
     * 车辆列表
     * @param $tempWhere
     * @param $nowPage
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function busList($tempWhere, $nowPage){
        $where = [];
        if ($tempWhere['business_id']){
            $where[] = ['business_id', '=', $tempWhere['business_id']];
        }
        if ($tempWhere['bus_no']){
            $where[] = ['bus_no', 'like', "%".$tempWhere['bus_no']."%"];
        }
        if (is_numeric($tempWhere['status'])){
            $where[] = ['status', '=', $tempWhere['status']];
        }
        if (is_numeric($tempWhere['state'])){
            $where[] = ['state', '=', $tempWhere['state']];
        }
        $busCount = $this->busModel->where($where)->count();
        if ($busCount > 0){
            $busList = $this->busModel->where($where)->page($nowPage, self::$pageNum)->select();
            foreach ($busList as $key=>$val){
                $busList[$key]->business_name = $val->business->name;
            }
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $busList, $busCount);
        } else{
            return ajaxArr(ErrorCode::$LISTNULL, '列表为空');
        }
    }

    /**
     * 车辆详情
     * @param $id
     * @return mixed
     */
    public function info($id){
        if ($id){
            $busInfo = $this->busModel->get($id);
            if ($busInfo){
                foreach ($busInfo->imgs as $key=>$val){
                    $img[] = $val->getData('img');
                }
                $imgStr = is_null($img)? "":implode(',', $img);
                $res['bus_info'] = $busInfo;
                $res['img_str'] = $imgStr;
                return ajaxArr(ErrorCode::$SUCCESS, 'success', $res);
            } else{
                return ajaxArr(ErrorCode::$INFONULL, '车辆信息不存在');
            }
        }
    }

    public function handle($data){
        $act = $data['act'];
        unset($data['act']);
        $res = false;
        switch ($act){
            case 'add':
                Db::startTrans();
                try{
                    $busRes = $this->busModel->allowField(true)->save($data);
                    if (!$busRes){
                        Db::rollback();
                        return ajaxArr(ErrorCode::$OPERATIONERROR, '添加车辆信息失败');
                    }
                    $bus = $this->busModel->find($busRes->id);
                    $imgArr = explode(',',$data['img_url']);
                    $imgData = [];
                    foreach ($imgArr as $key=>$val){
                        if ($val){
                            $temp['img'] = $val;
                            $imgData[] = $temp;
                        }
                    }
                    $imgRes = $bus->imgs()->saveAll($imgData);
                    if (!$imgRes){
                        Db::rollback();
                        return ajaxArr(ErrorCode::$OPERATIONERROR, '添加车辆图片失败');
                    }
                } catch (\Exception $e){
                    Db::rollback();
                    return ajaxArr(ErrorCode::$OPERATIONERROR, $e->getMessage());
                }
                Db::commit();
                $res = true;
                break;
            case 'edit':
                Db::startTrans();
                try{
                    $bus = $this->busModel->get($data['id']);
                    $busRes = $this->busModel->allowField(true)->save($data, ['id' => $data['id']]);

                    foreach ($bus->imgs as $key=>$val){
                        //软删除图片
                        BusImg::destroy($val->id);
                    }

                    $bus = $this->busModel->find($data['id']);
                    $imgArr = explode(',',$data['img_url']);
                    $imgData = [];
                    foreach ($imgArr as $key=>$val){
                        if ($val){
                            $temp['img'] = $val;
                            $imgData[] = $temp;
                        }
                    }
                    $imgRes = $bus->imgs()->saveAll($imgData);
                    if (!$imgRes || !$busRes){
                        Db::rollback();
                        return ajaxArr(ErrorCode::$OPERATIONERROR, '修改车辆信息失败');
                    }
                } catch (\Exception $e){
                    Db::rollback();
                    return ajaxArr(ErrorCode::$OPERATIONERROR, $e->getMessage());
                }
                Db::commit();
                $res = true;
                break;
            case 'del':
                Db::startTrans();
                try{
                    $bus = $this->busModel->get($data['id']);
                    $busRes = $bus->delete();
                    if(!$busRes){
                        Db::rollback();
                        return ajaxArr(ErrorCode::$OPERATIONERROR, '删除车辆失败');
                    }
                    foreach ($bus->imgs as $key=>$val){
                        //软删除图片
                        $imgRes = BusImg::destroy($val->id);
                        if (!$imgRes){
                            Db::rollback();
                            return ajaxArr(ErrorCode::$OPERATIONERROR, '删除车辆图片失败');
                        }
                    }
                } catch (\Exception $e){
                    return ajaxArr(ErrorCode::$OPERATIONERROR, $e->getMessage());
                }
                Db::commit();
                $res = true;
                break;
            case 'state':
                //审核车辆
                $busInfo = Bus::get($data['id']);
                $busInfo->state = $data['state'];
                $res = $busInfo->save();
                break;
            default:
                break;
        }
        if ($res){
            return ajaxArr(ErrorCode::$SUCCESS, '操作成功');
        }
    }

    /**
     * 根据查询条件获取所有车辆列表
     * @param $tempWhere
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBus($tempWhere){
        if ($tempWhere['business_id']){
            $where[] = ['business_id', '=', $tempWhere['business_id']];
        }
        if ($tempWhere['state']){
            $where[] = ['state', '=', $tempWhere['state']];
        }
        $busList = $this->busModel->where($where)->select();
        return ajaxArr(ErrorCode::$SUCCESS, 'success', $busList);
    }

}